import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 翻牌器计数器组件
/// 实现数字自动递增，带3D翻转动画效果
class FlipCounterWidget extends StatefulWidget {
  /// 初始值
  final int initialValue;

  /// 数字文本样式
  final TextStyle? textStyle;

  const FlipCounterWidget({super.key, this.initialValue = 0, this.textStyle});

  @override
  State<FlipCounterWidget> createState() => _FlipCounterWidgetState();
}

class _FlipCounterWidgetState extends State<FlipCounterWidget>
    with SingleTickerProviderStateMixin {
  late int _currentValue;
  late AnimationController _controller;
  Timer? _timer;
  final Random _random = Random();

  @override
  void initState() {
    super.initState();
    _currentValue = widget.initialValue;
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 600),
    );
    _startAutoIncrement();
  }

  @override
  void dispose() {
    _timer?.cancel();
    _controller.dispose();
    super.dispose();
  }

  /// 开始自动递增
  void _startAutoIncrement() {
    _scheduleNextIncrement();
  }

  /// 安排下一次递增
  void _scheduleNextIncrement() {
    // 随机间隔：2-5秒
    final delay = 2 + _random.nextDouble() * 3; // 2000-5000毫秒

    _timer?.cancel();
    _timer = Timer(Duration(milliseconds: (delay * 1000).round()), () {
      if (mounted) {
        _incrementValue();
        _scheduleNextIncrement();
      }
    });
  }

  /// 递增数值并触发动画
  void _incrementValue() {
    setState(() {
      _currentValue++;
    });
    _controller.forward(from: 0.0).then((_) {
      _controller.reset();
    });
  }

  @override
  Widget build(BuildContext context) {
    final textStyle =
        widget.textStyle ??
        TextStyle(
          fontSize: 24.sp,
          color: RazeConstants.black,
          fontWeight: FontWeight.bold,
        );

    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        final angle = _controller.value * pi;
        final isFlipped = angle > pi / 2;

        return SizedBox(
          height: textStyle.fontSize! * 1.2,
          child: Stack(
            children: [
              // 下半部分 - 显示旧值或新值的下半部分
              ClipRect(
                child: Align(
                  alignment: Alignment.bottomCenter,
                  heightFactor: 0.5,
                  child: Transform(
                    alignment: Alignment.bottomCenter,
                    transform:
                        Matrix4.identity()
                          ..setEntry(3, 2, 0.001)
                          ..rotateX(isFlipped ? 0 : angle),
                    child: Text(
                      (_currentValue - (isFlipped ? 1 : 0)).toString(),
                      style: textStyle,
                    ).applyNotoSans(weight: FontWeight.bold),
                  ),
                ),
              ),
              // 上半部分 - 显示旧值或新值的上半部分
              ClipRect(
                child: Align(
                  alignment: Alignment.topCenter,
                  heightFactor: 0.5,
                  child: Transform(
                    alignment: Alignment.topCenter,
                    transform:
                        Matrix4.identity()
                          ..setEntry(3, 2, 0.001)
                          ..rotateX(isFlipped ? angle - pi : 0),
                    child: Text(
                      (isFlipped ? _currentValue : _currentValue - 1)
                          .toString(),
                      style: textStyle,
                    ).applyNotoSans(weight: FontWeight.bold),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
